import time
from utils.log_manager import my_logger
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from drivers.driver_manager import driver
import os
import time
from PIL import Image
import platform

def clear_dir(path):
    """创建或清空目录"""
    if not os.path.isdir(path):
        os.mkdir(path)  # 创建目录
    else:  # 清空目录
        [os.remove(os.path.join(path, file_name)) for file_name in os.listdir(path)]
def base_dir():
    # 获取当前文件的目录
    base_dir = os.path.dirname(os.path.abspath(__file__))
    # 构造相对路径
    if platform.system() == "Windows":
        image_paths = "e:/report/images"
    elif platform.system() == "Darwin":  # macOS 系统返回的是 "Darwin"
        image_paths = os.path.join(base_dir, 'images')
    else:
        raise Exception("不支持的操作系统")
    return image_paths
IMG_INDEX = 1

class BasePage():


    def capt(self):
        global IMG_INDEX
        if IMG_INDEX >=100:
            return
        self.sleep(1)
        img_file = os.path.join(base_dir(), f'{IMG_INDEX}.png')
        print("截图路径",img_file)
        self.driver.save_screenshot(img_file)
        IMG_INDEX = IMG_INDEX + 1

    def sleep(self,num = 1):
        time.sleep(num)
    def __init__(self):
        self.driver = driver
        # self.img_num = 1

    # 打开指定url的网页
    def open(self,url):
        my_logger.logger.info("打开地址:{}", url)
        self.driver.get(url)
        self.sleep()
        self.capt()

    def find_element(self, locator):
        self.sleep()
        return self.driver.find_element(*locator)

    def find_elements(self, locator):
        self.sleep()
        return self.driver.find_elements(*locator)

    def click_element(self, locator):

        self.sleep()
        self.find_element(locator).click()
        self.capt()

    # 向目标元素输入文本
    def input_data(self, locator, text):
        self.sleep()
        el = self.find_element(locator)
        el.clear()
        el.send_keys(text)
        self.capt()


    def get_text(self, locator):
        return self.find_element(locator).text

    def get_texts(self, locator):
        return [el.text for el in self.find_elements(locator)]




    def get_source(self):
        """
        获取页面源码
        :return:
        """
        return self.driver.page_source


    # 鼠标移动到目标元素上悬停
    def move_mouse_to_element(self,value,by_type = By.XPATH):
        ActionChains(driver).move_to_element(self.find_element(by_type,value)).pause(2).perform()

    # 切换框架
    def switch_to_frame(self,id_name_or_element):
        self.driver.switch_to.frame(id_name_or_element)

    # 切换窗口
    def switch_to_window(self,title):
        handles = driver.window_handles
        for handle in handles:
            self.driver.switch_to.window(handle)
            if self.driver.title == title:
                break

    # 删除cookies
    def del_cookis(self):
        self.driver.delete_all_cookies()
        self.capt()

        # 关闭当前页面
    def close(self):
        self.capt()
        self.driver.close()

        # 退出浏览器，关闭所有页面
    def quit(self):
        print("退出浏览器，关闭所有页面")
        my_logger.logger.info("退出浏览器，关闭所有页面")
        self.capt()
        self.driver.quit()
    def refresh(self):
        print("刷新浏览器",self.driver.current_url)
        my_logger.logger.info("刷新浏览器,{}",self.driver.current_url)
        self.driver.refresh()
        self.capt()

    def is_element_present(self, locator, timeout=3):
        """
        判断元素是否存在
        :param locator: 元素定位元组，如 (By.ID, "xxx")
        :param timeout: 查找等待时间（秒），可根据需要修改
        :return: True 或 False
        """
        self.driver.implicitly_wait(timeout)
        try:
            self.find_element(locator)
            return True
        except NoSuchElementException:
            return False
        finally:
            self.driver.implicitly_wait(0)  # 避免影响后续
